// utils/request.ts 或 utils/api.ts

// const API_BASE_URL = 'http://192.168.2.11:8080';
const API_BASE_URL = 'https://tour.dwtcy.com.cn';
const request = (url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD', data: any = {}) => {
  return new Promise((resolve, reject) => {
    const header: Record<string, string> = {
      'Content-Type': 'application/json'
    };

    // ✅ 只要存在 token，就自动带上
    const token = wx.getStorageSync('token');
    if (token) {
      header['Authorization'] = `Bearer ${token}`;
    }
    
    wx.request({
      url: API_BASE_URL + url,
      method,
      data,
      header,
      success(res) {
        
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          resolve(res.data);
        } else {
          let msg = '请求失败';
          if (typeof res.data === 'object' && res.data !== null) {
            msg = (res.data as Record<string, any>).message || (res.data as Record<string, any>).msg || msg;
          }
          wx.showToast({ title: msg, icon: 'none' });
          reject(res.data);
        }
      },
      fail(error) {
        wx.showToast({ title: '网络异常', icon: 'none' });
        reject(error);
      }
    });
  });
};

// 封装具体接口
const getModel = (data = {}) => {
  return request('/api/wx/model/list', 'GET', data);
};

const geyGoodsById = (id: number, data = {}) => {
  return request(`/api/wx/goods/${id}`, 'GET', data);
};
const getGoodsList = (data = {}) => {
  return request(`/api/wx/goods/list`, 'GET', data);
};
// 商户列表（后端返回全量）
const getMerchantList = (data = {}) => {
  return request(`/api/wx/merchant/list`, 'GET', data);
};
// 根据商户ID获取产品/剧本列表
const getProductsByMerchant = (merchantId: number) => {
  return request(`/api/wx/product/${merchantId}`, 'GET');
};

//获取消息记录
const getMessages = (toUsername: string,data = {})=>{
  return request(`/api/chat/messages?toUsername=${toUsername}`,'GET',data);
}

// 创建支付订单
const createPayOrder = (goodsId: number, count: number) => {
  return request('/api/wx/pay/order', 'POST', {
    goodsId,
    count
  });
};

//绑定业务员和微信用户
const bindSalesmanWXUser = (scene:string)=>{
  return request(`/api/user/bind?scene=${scene}`,'GET');
}

export default {
  getModel,
  getGoodsList,
  geyGoodsById,
  getMerchantList,
  getProductsByMerchant,
  getMessages,
  createPayOrder,
  bindSalesmanWXUser
};;